import { CurrentUser } from '@/decorators';
import {
  PublisherCreateDto,
  PublisherFindDto,
  PublisherQueryDto,
  PublisherRemoveDto,
  PublisherUpdateDto,
  PublisherUserFollowsQueryDto,
} from '@/dtos';
import { PublisherService } from '@/services/publisher.service';
import { halt, ok } from '@/utils';
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { BaseController } from './base.controller';

@Controller('publisher')
export class PublisherController extends BaseController {
  constructor(private readonly publisherService: PublisherService) {
    super();
  }

  @Post('user/follows')
  async getUserFollows(
    @Body() dto: PublisherUserFollowsQueryDto,
    @CurrentUser('id') userId: number,
  ) {
    return ok(await this.publisherService.getUserFollows(userId, dto));
  }

  @Get('detail/:id')
  async getDetail(@Param('id') id: number, @CurrentUser('id') userId: number) {
    const data = (await this.publisherService.findOne(
      {
        id,
        isDeleted: false,
      },
      {
        id: true,
        name: true,
        logo: true,
        image: true,
        detail: true,
        labels: true,
      },
    )) as any;
    if (!data) {
      return halt('数据异常');
    }
    const followCount = await this.prisma.userFollowPublisher.count({
      where: {
        publisherId: id,
      },
    });
    const isFollow = await this.prisma.userFollowPublisher.findFirst({
      where: {
        userId,
        publisherId: id,
      },
    });
    return ok({
      ...data,
      followCount,
      isFollow: !!isFollow,
    });
  }

  @Post('follow/:id')
  async follow(@Param('id') id: number, @CurrentUser('id') userId: number) {
    const data = await this.prisma.userFollowPublisher.findFirst({
      where: {
        userId,
        publisherId: id,
      },
    });
    if (!!data) {
      await this.prisma.userFollowPublisher.deleteMany({
        where: {
          userId,
          publisherId: id,
        },
      });
    } else {
      await this.prisma.userFollowPublisher.create({
        data: {
          userId,
          publisherId: id,
        },
      });
    }
    return ok(true);
  }

  @Post('admin/query')
  async query(@Body() dto: PublisherQueryDto) {
    return ok(await this.publisherService.query(dto));
  }

  @Post('admin/find')
  async find(@Body() dto: PublisherFindDto) {
    return ok(await this.publisherService.findOne(dto.where, dto.select));
  }

  @Post('admin/create')
  async create(@Body() dto: PublisherCreateDto) {
    return ok(await this.publisherService.create(dto.data));
  }

  @Patch('admin/update')
  async update(@Body() dto: PublisherUpdateDto) {
    return ok(await this.publisherService.update(dto));
  }

  @Delete('admin/remove')
  async remove(@Query() dto: PublisherRemoveDto) {
    return ok(await this.publisherService.remove(dto));
  }
}
